package cn.donting.plugin.spring.boot.starter.configuration;

import cn.donting.plugin.spring.boot.starter.dev.DevPluginLoader;
import cn.donting.plugin.spring.boot.starter.plugin.autoconfiguration.resource.PluginResource;
import cn.donting.plugin.spring.boot.starter.properties.PluginProperties;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.lang.Nullable;

import java.util.Map;

/**
 * 主程序Application
 *
 * @author donting
 * 2020-06-23 16:26
 */

public class MainApplication {

    private static ApplicationContext applicationContext;
    private static boolean isInit = false;
    private static boolean isDev;
    private static Map<String, PluginResource> pluginResourceMap;

    public MainApplication(ApplicationContext applicationContext) {
        if (!isInit) {
            MainApplication.applicationContext = applicationContext;
            MainApplication.pluginResourceMap = MainApplication.getBeansOfType(PluginResource.class);
            try {
                applicationContext.getBean(DevPluginLoader.class);
                isDev = true;
            } catch (BeansException beansException) {
                isDev = false;
            }
        }
    }


    /**
     * 是否开发环境
     *
     * @return
     */
    public static boolean isDev() {
        return isDev;
    }

    /**
     * 获取主程序 容器中的 类
     *
     * @param type Class
     * @param <T>  T
     * @return bean
     * @throws BeansException BeansException
     */
    public static <T> Map<String, T> getBeansOfType(@Nullable Class<T> type) throws BeansException {
        return applicationContext.getBeansOfType(type);
    }

    /**
     * 获取 插件配置文件
     *
     * @return PluginProperties
     */
    public static PluginProperties getPluginProperties() {
        return applicationContext.getBean(PluginProperties.class);
    }

}
